import java.io.EOFException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class QOGThread extends Thread 
{
	String query;
	Connection con;
	DatabaseConnect dc;
	Shalatik bot;
	boolean running = true;
	String channel;
	
	String prevnick = null;
	String prevword = null;
	Long prevtime = null;
	
	public QOGThread(Connection con, Shalatik bot, String channel)
	{
		this.con = con;
		this.bot = bot;
		this.channel = channel;
	}
	
	boolean checkSpam(ResultSet rs)
	{
		return true;
	}
	
	public synchronized void  run()
	{
		try {
			dc = new DatabaseConnect(con);
			while (running)
			{
				wait(900000);
				System.out.println("[debug] checking QOG pending list");												
				query = "SELECT * FROM irc_qog_pending";			
				ResultSet rs = dc.sendQuery(query);				
				while(rs.next())
				{
					if (prevnick == null)
					{
						System.out.println("[debug] update: "+rs.getString("nick")+" "+rs.getFloat("value"));
						bot.updateQOG(rs.getString("nick"), rs.getFloat("value"), channel);						
					}
					else if (prevnick.equals(rs.getString("nick")) &&							 
							 (rs.getLong("time") - prevtime) < 3000)
					{
						System.out.println("[debug] spam - nepridavam");
					}
					else
					{
						System.out.println("[debug] update: "+rs.getString("nick")+" "+rs.getFloat("value"));
						bot.updateQOG(rs.getString("nick"), rs.getFloat("value"), channel);
					}
					
					prevnick = rs.getString("nick");
					prevword = rs.getString("word");
					prevtime = rs.getLong("time");
					
					query = "DELETE FROM irc_qog_pending WHERE id = "+rs.getInt("id");
					dc.sendUpdateQuery(query);
				}
				rs.close();
			}			
		} catch (InterruptedException e) {			
			e.printStackTrace();
		} catch (EOFException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void turnOff()
	{
		running = false;
	}
}
